//
//  MainViewController.swift
//  sinaWeiBo
//
//  Created by smartlei on 15/10/14.
//  Copyright © 2015年 smartlei. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
  
        //添加子控制器
        addChildViewControllers()
        //添加中心按钮
        setupComposeButton()
        
    }
   
    //重写view出现方法
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //让tabBar将按钮带到前端
        tabBar.bringSubviewToFront(composedButton)
        
        
    }
    
    // MARK: - 懒加载中心按钮控件
    private lazy var composedButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        return btn
        
    }()
    //MARK: - 按钮点击事件
    @objc  private func composedBtnClick() {
        print("点击我了")
    }
}
//MARK - 设置主界面
extension MainViewController {
    //添加中心按钮
    private func setupComposeButton() {
        
        //1 向tabBar添加子控制器
        tabBar.addSubview(composedButton)
        
        //2 设置frame
        let count = childViewControllers.count
        //print(tabBar.subviews)
        //3 计算每个按钮的宽度
        let btnW = tabBar.bounds.width / CGFloat(count) - 1
        //4 设置frame
        composedButton.frame = CGRectInset(tabBar.bounds, 2 * btnW, 0)
        //5 添加点击事件
        composedButton.addTarget(self, action: "composedBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    //添加多个控制器
    private func addChildViewControllers() {
        //0 tabBar渲染
        // 设置 tintColor － 图片渲染颜色
        // 性能提升的技巧 - 如果能够用颜色解决，就不建议使用图片
      //  tabBar.tintColor = UIColor.orangeColor()
        
        //1 添加主页
        addChildViewController(HomeTableViewController(), title: "首页", imgName: "tabbar_home")
        //2 添加消息
        addChildViewController(MessageTableViewController(), title: "消息", imgName: "tabbar_message_center")
        //5 添加中心控制器
        addChildViewController(UITableViewController())
        
        //3添加发现
        addChildViewController(DiscoverTableViewController(), title: "发现", imgName: "tabbar_discover")
        //4添加我
        addChildViewController(MeTableViewController(), title: "我", imgName: "tabbar_profile")
        
    }
    
    
    //添加单独控制器
    private func addChildViewController(vc: UIViewController,title: String,imgName: String) {
        
        //添加渲染
        
        //1 创建VC
       // let vc = DiscoverViewController()
        //2  设置标题
        vc.title = title
        //3 设置按钮
        vc.tabBarItem.image = UIImage(named: imgName)
        //4 创建
        let nvc = UINavigationController(rootViewController: vc)
        
        addChildViewController(nvc)
 
    }
}


